package com.peas.platform.common.core.component;

import com.peas.platform.common.core.configuration.RequestContext;
import com.peas.platform.common.core.configuration.RequestContextUtil;
import com.peas.platform.common.core.constant.Constants;
import com.peas.platform.common.core.utils.RequestUtil;
import lombok.SneakyThrows;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.function.Function;

public class FutureTaskCall<T, R> {

    private final RequestContext rc;

    public FutureTaskCall() {
        this.rc = RequestContextUtil.getRequestContext();
    }

    public void submitAsync(final Function<T, R> fun, final T arg) {
        Callable<R> call = () -> {
            RequestUtil.initRequestId(rc);
            return fun.apply(arg);
        };
        FutureTask<R> task = new FutureTask<>(call);
        Constants.executor.submit(task);
    }

    @SneakyThrows
    public R submit(final Function<T, R> fun, final T arg) {
        Callable<R> call = () -> {
            RequestUtil.initRequestId(rc);
            return fun.apply(arg);
        };
        FutureTask<R> task = new FutureTask<>(call);
        Constants.executor.submit(task);
        return task.get();
    }

}
